import os

import aiofiles
from fastapi import UploadFile

from env_config import settings
from exceptions.base import AppException
from http_base import HttpResp

SIZE = 8192


class LocalStorage:

    @classmethod
    async def upload(cls, file_in: UploadFile, key: str):
        directory = settings.upload_directory
        paths = key.split('/')
        save_name = paths[-1]
        _date = paths[-2]
        folder = '/'.join(paths[:-2])
        save_path = os.path.join(directory, folder, _date).replace('\\', '/')
        file_name = os.path.join(save_path, save_name).replace('\\', '/')

        if not os.path.exists(save_path):
            os.makedirs(save_path, exist_ok=True)  # 使用 exist_ok=True 以避免文件夹已存在的异常
        try:
            async with aiofiles.open(file_name, 'wb') as file_out:
                while True:
                    content = await file_in.read(SIZE)
                    if not content:
                        break
                    await file_out.write(content)
        except Exception as e:
            raise AppException(HttpResp.FAILED, msg='上传文件失败:%s' % e)
        finally:
            try:
                await file_in.close()  # 确保文件对象关闭
                print(f"File closed successfully: {file_in.filename}")
            except Exception as e:
                print(f"Exception while closing file: {e}")
